<?php 
//I.F. Nuevo: 2011-02-28; ramarin
require_once('../../../config.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot.'/'.$CFG->admin.'/report/moosisca/managecourseslib.php');
require_once($CFG->dirroot . '/course/lib.php');

global $USER;

if ($frm = data_submitted() and confirm_sesskey()) {
  $coursesIds = array();
  
  foreach($frm as $key => $input){
    $pos = strpos($key, "chkCourse_");
    
    if($pos !== false){
      $coursesIds[] = substr($key, strpos($key, '_') + 1, strlen($key) - strpos($key, '_'));
    }
  }
  
  foreach($coursesIds as $id){    
    $workflow = get_records('moosisca_workflow', 'id', $id);    
    
    if(!empty($workflow)){
      $workflow = $workflow[$id];
      $workflow->state = 'evaluation';
      $workflow->userid = $USER->id;
      
      if(update_record('moosisca_workflow', $workflow)){
        $history = new stdClass();
        $history->workflowid = $workflow->id;
        $history->state = 'evaluation';
        $history->userid = $USER->id;
        $history->observations = '';
        $history->timecreated = time();
        
        if(insert_record('moosisca_workflow_history', $history)){
          $success = 1;
        }
        else{
          $workflow->state = 'created';
          update_record('moosisca_workflow', $workflow);
        }
      }
      else {
        notice(get_string('requestevaluationfailed', 'report_moosisca'));
      }
    }
    else{
      notice(get_string('requestevaluationfailed', 'report_moosisca'));
    }
  }  
    
  if(!empty($success)){
    notice(get_string('successfulloperation', 'report_moosisca'));
  }
}

$systemcontext = get_context_instance(CONTEXT_SYSTEM);

echo '<form name="courseevaluationrequestform" id="courseevaluationrequestform" method="post" action="courseevaluationrequest.php">';
echo '<input type="hidden" name="sesskey" value="'.sesskey().'"/>';

print_my_courses();

echo '</form>';
  
function print_my_courses() {
  global $CFG, $USER;
  
  $courses = get_pending_approvation_courses('mw.id, c.fullname, mw.state', "mw.state='evaluation'");
  
  if($courses) {  
    print_heading(get_string('pendingApprovedCourses', 'report_moosisca'));
  
    $table->head = array (get_string("course"), get_string("state", "report_moosisca"), get_string("action"));
    $table->align = array ("left", "left", "center");
    $table->width = "60%";
    
    foreach($courses as $course){      
      $state = get_string('workFlowState.' . $course["state"], 'report_moosisca');      
      $viewbutton = "<a href=\"javascript:var params = new Array(); params['id']='" . $course['id'] . "'; load_report_detail(params,'approve_course');\" >" . get_string('approveCourse', 'report_moosisca') . "</a>";

      $table->data[] = array (format_string($course["fullname"]),
                $state,
                $viewbutton);
    }
    
    print_table($table);
  }
  else {
    print_heading(get_string('noPendingApprovedCoursesFound', 'report_moosisca'));
  }
}
?>